<?php

namespace app\http\controller\admin;

use Laf\Session;
use FApi\Response;
use app\libs\View;
use Laf\Controller;
use mon\env\Config;
use mon\captcha\Captcha;
use app\model\AdminModel;

/**
 * 开放控制器
 * 
 * @author Mon <985558837@qq.com>
 * @version 1.0.0
 */
class PassportController extends Controller
{
    /**
     * 判断是否登录切换页面
     *
     * @return string
     */
    public function identify()
    {
        if (Session::instance()->getService()->get(Config::instance()->get('admin.admin_session_key'))) {
            // 判断是否存在refer，存在ref则携带refer进行跳转
            $refer = $this->request->get('refer', false);
            $indexURL = $this->url->build('/admin/console', $refer ? ['refer' => $refer] : []);
            return $this->url->redirect($indexURL);
        }

        $loginURL = $this->url->build('/admin/login');
        return $this->url->redirect($loginURL);
    }

    /**
     * 用户登陆
     *
     * @return string
     */
    public function login(AdminModel $model)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 非开发环境，验证图片验证码
            if (RUN_MODE != 'dev') {
                if (!isset($data['captcha']) || empty($data['captcha'])) {
                    return $this->error('验证码参数错误');
                }
                $config = Config::instance()->get('captcha');
                $captcha = new Captcha($config);
                $id = Config::instance()->get('admin.login_captcha_id');
                if (!$captcha->check($data['captcha'], $id)) {
                    return $this->error('验证码错误');
                }
            }

            $userInfo = $model->login($data);
            if (!$userInfo) {
                return $this->error($model->getError());
            }

            Session::instance()->getService()->set(Config::instance()->get('admin.admin_session_key'), $userInfo);
            $refer = $this->request->get('refer', false);
            $indexURL = $this->url->build('/admin/console', $refer ? ['refer' => $refer] : []);
            return $this->success('ok', ['url' => $indexURL]);
        }

        $view = new View(APP_PATH . '/view/admin/');
        $view->assign('site', Config::instance()->get('admin.site'));
        return $view->fetch('login');
    }

    /**
     * 获取验证码
     *
     * @return void
     */
    public function captcha()
    {
        $id = Config::instance()->get('admin.login_captcha_id');
        $config = Config::instance()->get('captcha');
        $captcha = new Captcha($config);
        $data = $captcha->create($id, false);
        return Response::create($data)->header(['Content-Type' => 'image/png']);
    }

    /**
     * 用户登出
     *
     * @return string
     */
    public function logout()
    {
        Session::instance()->getService()->clear();
        $url = $this->url->build('/admin/login');
        return $this->url->redirect($url);
    }
}
